<template>
  <div class="sql-editor-container">
    <div v-if="isShowSqlFormatButton" class="sql-btn">
      <a-button @click="handleFormatSql">SQL格式化</a-button>
    </div>
    <div class="sql-editor-container">
      <codemirror ref="sqlEditor" class="sql-editor" v-model="sqlContent" :options="cmOptions"></codemirror>
    </div>
  </div>
</template>

<script>
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/keymap/sublime' // sublime编辑器效果
import 'codemirror/theme/darcula.css'// 配置里面也需要theme设置为monokai
import 'codemirror/mode/sql/sql.js' // 配置里面也需要mode设置为vue
import 'codemirror/addon/selection/active-line' // 光标行背景高亮，配置里面也需要styleActiveLine设置为true
// sql format
import { format } from 'sql-formatter'

export default {
  name: 'SQLEditor',
  components: { codemirror },
  props: {
    sqlString: {
      type: String,
      default: ''
    },
    isShowSqlFormatButton: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      sqlContent: this.sqlString,
      cmOptions: {
        tabSize: 4, // tab的空格个数
        theme: 'darcula', // 主题样式
        lineNumbers: true, // 是否显示行数
        lineWrapping: true, // 是否自动换行
        styleActiveLine: true, // line选择是是否加亮
        matchBrackets: true, // 括号匹配
        mode: 'sql', // 实现sql代码高亮
        readOnly: false // 只读
      }
    }
  },
  watch: {
    sqlContent: {
      handler(newValue, oldValue) {
        if (newValue !== oldValue) this.$emit('input', newValue)
      },
      immediate: true
    }
  },
  methods: {
    /**
     * @description 格式化sql语句
     * @returns void
     */
    handleFormatSql() {
      this.sqlContent = format(this.sqlContent)
    },

    /**
     * @description 返回处理之后的值
     * @returns {String}  sql
     */
    handleReturnValue() {
      return this.sqlContent
    },

    /**
     * @description 清空
     * @returns void
     */
    handleEmptySqlContent() {
      this.sqlContent = ''
    },

    /**
     * @description 在指定位置插入数据
     * @param {*} value
     * @return void
     */
    handleInsertToValue(value) {
      const positionFirst = this.$refs.sqlEditor.codemirror.getCursor()
      const positionTwo = {
        line: positionFirst.line,
        ch: positionFirst.ch
      }
      this.$refs.sqlEditor.codemirror.replaceRange(value, positionTwo)
    }
  }

}
</script>

<style lang="less" scoped>
.sql-editor-container {
  position: absolute;
  width: 100%;
  height: 100%;
  .sql-btn {
    width: 100%;
    height: 36px;
    text-align: right;
  }
  .sql-editor-container {
    height: calc(100% - 40px);
    width: 100%;
    .sql-editor {
      font-size: 15px;
      width: 100%;
      height: 100%;
    }
  }
}
</style>

<style lang="less">
.sql-editor {
  .CodeMirror {
    height: 100%;
  }
}
</style>
